<template>
  <Dialog v-model="dialogVisible" title="实时监控" width="1400px">
    <!-- 监控概览 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-card class="monitor-card">
          <el-statistic title="在线考试场次" :value="monitoringData.onlineExams" prefix="🏫" />
          <div class="card-status">
            <el-tag type="success">正常</el-tag>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="monitor-card">
          <el-statistic title="在线考生数量" :value="monitoringData.onlineCandidates" prefix="👥" />
          <div class="card-status">
            <el-tag type="success">正常</el-tag>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="monitor-card">
          <el-statistic title="系统CPU使用率" :value="monitoringData.cpuUsage" suffix="%" prefix="💻" />
          <div class="card-status">
            <el-tag :type="monitoringData.cpuUsage > 80 ? 'danger' : 'success'">
              {{ monitoringData.cpuUsage > 80 ? '高负载' : '正常' }}
            </el-tag>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="monitor-card">
          <el-statistic title="网络延迟" :value="monitoringData.networkLatency" suffix="ms" prefix="🌐" />
          <div class="card-status">
            <el-tag :type="monitoringData.networkLatency > 500 ? 'warning' : 'success'">
              {{ monitoringData.networkLatency > 500 ? '较慢' : '良好' }}
            </el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 控制面板 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>监控控制</span>
          </template>
          <el-space wrap>
            <el-button 
              :type="isMonitoring ? 'danger' : 'primary'" 
              @click="toggleMonitoring"
              :loading="controlLoading"
            >
              {{ isMonitoring ? '停止监控' : '开始监控' }}
            </el-button>
            <el-button type="success" @click="refreshData" :loading="refreshLoading">
              刷新数据
            </el-button>
            <el-button type="warning" @click="clearAlerts">
              清除警告
            </el-button>
            <el-button @click="exportReport">
              导出报告
            </el-button>
          </el-space>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>监控设置</span>
          </template>
          <el-space wrap>
            <el-select v-model="monitoringSettings.refreshInterval" placeholder="刷新间隔" size="small">
              <el-option label="5秒" :value="5" />
              <el-option label="10秒" :value="10" />
              <el-option label="30秒" :value="30" />
              <el-option label="1分钟" :value="60" />
            </el-select>
            <el-switch
              v-model="monitoringSettings.autoAlert"
              active-text="自动报警"
              inactive-text="手动报警"
            />
            <el-switch
              v-model="monitoringSettings.soundAlert"
              active-text="声音提醒"
              inactive-text="静音模式"
            />
          </el-space>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 实时数据图表 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>系统性能趋势</span>
          </template>
          <div ref="performanceChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>考生活动分布</span>
          </template>
          <div ref="activityChartRef" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 实时告警 -->
    <el-card style="margin-bottom: 20px;">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>实时告警 ({{ alerts.length }})</span>
          <el-tag :type="getAlertLevelColor()" v-if="alerts.length > 0">
            {{ getAlertLevel() }}
          </el-tag>
        </div>
      </template>
      <el-table :data="alerts.slice(0, 5)" style="width: 100%" max-height="200">
        <el-table-column prop="time" label="时间" width="150" />
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlertTypeColor(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column prop="message" label="告警信息" />
        <el-table-column label="操作" width="120">
          <template #default="{ row, $index }">
            <el-button link type="primary" size="small" @click="handleAlert(row, $index)">
              处理
            </el-button>
            <el-button link type="danger" size="small" @click="ignoreAlert($index)">
              忽略
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 在线考试列表 -->
    <el-card>
      <template #header>
        <span>在线考试监控</span>
      </template>
      <el-table :data="onlineExams" style="width: 100%">
        <el-table-column prop="examName" label="考试名称" width="200" />
        <el-table-column prop="location" label="考试地点" width="150" />
        <el-table-column prop="startTime" label="开始时间" width="150" />
        <el-table-column prop="candidateCount" label="考生数量" width="100" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getExamStatusColor(row.status)">
              {{ getExamStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :color="getProgressColor(row.progress)" />
          </template>
        </el-table-column>
        <el-table-column label="网络状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.networkStatus === 'good' ? 'success' : 'warning'">
              {{ row.networkStatus === 'good' ? '良好' : '不稳定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="viewExamDetail(row)">
              详情
            </el-button>
            <el-button link type="warning" size="small" @click="sendNotice(row)">
              通知
            </el-button>
            <el-button link type="danger" size="small" @click="emergencyStop(row)">
              紧急停止
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const dialogVisible = ref(false)
const isMonitoring = ref(false)
const controlLoading = ref(false)
const refreshLoading = ref(false)
let monitoringTimer: any = null

const monitoringData = ref({
  onlineExams: 5,
  onlineCandidates: 128,
  cpuUsage: 65,
  networkLatency: 120
})

const monitoringSettings = ref({
  refreshInterval: 10,
  autoAlert: true,
  soundAlert: false
})

const performanceChartRef = ref()
const activityChartRef = ref()

const alerts = ref([
  {
    time: '14:25:33',
    level: '警告',
    source: '考场A',
    message: '网络延迟超过500ms'
  },
  {
    time: '14:20:15',
    level: '信息',
    source: '系统',
    message: '新考生登录：张三'
  },
  {
    time: '14:18:42',
    level: '错误',
    source: '考场B',
    message: '考生设备离线'
  }
])

const onlineExams = ref([
  {
    id: '1',
    examName: '2023年电工技能评价',
    location: '考场A',
    startTime: '14:00:00',
    candidateCount: 32,
    status: 'ongoing',
    progress: 75,
    networkStatus: 'good'
  },
  {
    id: '2',
    examName: '2023年焊工技能评价',
    location: '考场B',
    startTime: '14:30:00',
    candidateCount: 28,
    status: 'ongoing',
    progress: 45,
    networkStatus: 'unstable'
  }
])

const getAlertLevel = () => {
  const hasError = alerts.value.some(alert => alert.level === '错误')
  const hasWarning = alerts.value.some(alert => alert.level === '警告')
  
  if (hasError) return '严重'
  if (hasWarning) return '警告'
  return '正常'
}

const getAlertLevelColor = () => {
  const level = getAlertLevel()
  const colorMap = { '严重': 'danger', '警告': 'warning', '正常': 'success' }
  return colorMap[level] || 'info'
}

const getAlertTypeColor = (level: string) => {
  const colorMap = { '错误': 'danger', '警告': 'warning', '信息': 'info' }
  return colorMap[level] || 'info'
}

const getExamStatusName = (status: string) => {
  const statusMap = { 'ongoing': '进行中', 'completed': '已完成', 'paused': '已暂停' }
  return statusMap[status] || '未知'
}

const getExamStatusColor = (status: string) => {
  const colorMap = { 'ongoing': 'success', 'completed': 'info', 'paused': 'warning' }
  return colorMap[status] || 'info'
}

const getProgressColor = (progress: number) => {
  if (progress >= 80) return '#67c23a'
  if (progress >= 50) return '#e6a23c'
  return '#f56c6c'
}

const toggleMonitoring = () => {
  controlLoading.value = true
  setTimeout(() => {
    isMonitoring.value = !isMonitoring.value
    if (isMonitoring.value) {
      startMonitoring()
    } else {
      stopMonitoring()
    }
    controlLoading.value = false
  }, 1000)
}

const startMonitoring = () => {
  monitoringTimer = setInterval(() => {
    refreshData()
  }, monitoringSettings.value.refreshInterval * 1000)
  ElMessage.success('实时监控已启动')
}

const stopMonitoring = () => {
  if (monitoringTimer) {
    clearInterval(monitoringTimer)
    monitoringTimer = null
  }
  ElMessage.info('实时监控已停止')
}

const refreshData = () => {
  refreshLoading.value = true
  setTimeout(() => {
    // 模拟数据更新
    monitoringData.value = {
      onlineExams: Math.floor(Math.random() * 3) + 4,
      onlineCandidates: Math.floor(Math.random() * 50) + 100,
      cpuUsage: Math.floor(Math.random() * 40) + 50,
      networkLatency: Math.floor(Math.random() * 200) + 80
    }
    refreshLoading.value = false
    ElMessage.success('数据已刷新')
  }, 500)
}

const clearAlerts = () => {
  alerts.value = []
  ElMessage.success('告警已清除')
}

const exportReport = () => {
  ElMessage.info('报告导出功能开发中...')
}

const handleAlert = (alert: any, index: number) => {
  ElMessage.success(`正在处理告警：${alert.message}`)
  alerts.value.splice(index, 1)
}

const ignoreAlert = (index: number) => {
  alerts.value.splice(index, 1)
  ElMessage.info('告警已忽略')
}

const viewExamDetail = (exam: any) => {
  ElMessage.info(`查看考试详情：${exam.examName}`)
}

const sendNotice = (exam: any) => {
  ElMessage.success(`已向${exam.examName}发送通知`)
}

const emergencyStop = (exam: any) => {
  ElMessageBox.confirm(`确定要紧急停止${exam.examName}吗？`, '确认操作', {
    type: 'warning'
  }).then(() => {
    ElMessage.success(`${exam.examName}已紧急停止`)
    exam.status = 'paused'
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

const initCharts = () => {
  // TODO: 初始化ECharts图表
  console.log('初始化监控图表')
}

const open = () => {
  dialogVisible.value = true
  initCharts()
}

onMounted(() => {
  // 组件挂载时的初始化
})

onUnmounted(() => {
  // 清理定时器
  if (monitoringTimer) {
    clearInterval(monitoringTimer)
  }
})

defineExpose({ open })
</script>

<style scoped>
.monitor-card {
  text-align: center;
  position: relative;
}

.card-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

:deep(.el-statistic__number) {
  font-size: 28px;
}

:deep(.el-card__header) {
  padding: 12px 20px;
}

.el-progress {
  margin: 0;
}
</style> 